import Http from "../network/Http";
import SDKManager, { Platform } from "./SDKManager";
import EventManager from "../EventManager";
import { OppoConfig } from "./oppo/OppoConfig";
import { TouTiaoConfig } from "./toutiao/TouTiaoConfig";
import { WeiXinConfig } from "./weixin/WeiXinConfig";
import CommonUtils from "../CommonUtils";

export const EventOnRemoteConfigLoaded = 'EventOnRemoteConfigLoaded';

export enum ADType {
    Banner, Video, Insert
}

const USE_RELEASE_CONFIG = true;

export default class QuLe {
    static readonly PlatWeiXin = 'weixin';
    static readonly PlatTouTiao = 'toutiao';
    static readonly PlatOppo = 'oppo';

    private static _instance: QuLe = null;
    private constructor() { }
    static get instance() {
        if (!QuLe._instance) {
            QuLe._instance = new QuLe();
        }
        return QuLe._instance;
    }

    isLogined = false;
    uid: string;
    session: string;
    loginName: string;
    remoteConfig: any;
    get isLoadedRemoteConfig(): boolean { return this.remoteConfig; }

    canRecordBannerOnceAfterLogin = false;
    canRecordVideoOnceAfterLogin = false;
    canRecordInsertOnceAfterLogin = false;

    /** 加载远程配置,完成后才能登录趣乐(编辑器环境将config.json放入resources/configs目录下测试), onFinish(success: boolean), 完成后会触发全局事件: EventOnRemoteConfigLoaded
     * @param onFinish true/false
     */
    loadRemoteConfig(onFinish?: Function) {
        if (this.remoteConfig) {
            onFinish && onFinish(true);
            return;
        }
        console.log("SDKConfig.IS_RELEASE:", USE_RELEASE_CONFIG)
        if (SDKManager.platform != Platform.Other) {
            let url = this.getRemoteConfigUrl() + '/config.json';
            Http.get(url, (success: boolean, res: string) => {
                if (success) {
                    this.remoteConfig = USE_RELEASE_CONFIG ? JSON.parse(res).release : JSON.parse(res).debug;
                    console.log('远程配置：' + JSON.stringify(this.remoteConfig))
                    EventManager.emit(EventOnRemoteConfigLoaded);
                    onFinish && onFinish(true);
                } else {
                    console.error('加载远程配置失败');
                    onFinish && onFinish(false);
                }
            })
        } else {
            cc.loader.loadRes('configs/config', cc.JsonAsset, (err, res: cc.JsonAsset) => {
                if (err) {
                    console.error(err);
                    onFinish && onFinish(false);
                    return;
                }
                this.remoteConfig = USE_RELEASE_CONFIG ? res.json.release : res.json.debug;
                console.log('远程配置：' + JSON.stringify(this.remoteConfig))
                EventManager.emit(EventOnRemoteConfigLoaded);
                onFinish && onFinish(true);
            })
        }
    }

    getRemoteConfigUrl() {
        switch (SDKManager.platform) {
            case Platform.WeiXin:
                return WeiXinConfig.REMOTE_RES_URL;
            case Platform.TouTiao:
                return TouTiaoConfig.REMOTE_RES_URL;
            case Platform.Oppo:
                return OppoConfig.REMOTE_RES_URL;
        }
        return WeiXinConfig.REMOTE_RES_URL;
    }

    /** 获取远程配置表里的分享标题 */
    get randomShareTitle() {
        if (this.remoteConfig && this.remoteConfig.shareTitles) {
            let index = CommonUtils.randomInt(0, this.remoteConfig.shareTitles.length);
            return this.remoteConfig.shareTitles[index];
        }
        return "";
    }

    /**
     * 登录
     * @param onFinish 登录成功返回true
     */
    login(onFinish: Function) {
        if (this.isLogined) {
            onFinish && onFinish(true);
            return;
        }
        console.log('开始登录趣乐');
        let plat = '';
        switch (SDKManager.platform) {
            case Platform.WeiXin:
                plat = QuLe.PlatWeiXin;
                break;
            case Platform.TouTiao:
                plat = QuLe.PlatTouTiao;
                break;
            case Platform.Oppo:
                plat = QuLe.PlatOppo;
                break;
        }
        let openid = SDKManager.instance.openid;
        if (!openid) {
            openid = '';
        }
        let session = SDKManager.instance.session;
        if (!session) {
            session = '';
        }
        let session2 = SDKManager.instance.session2;
        if (!session2) {
            session2 = '';
        }
        let loginname = SDKManager.instance.loginname;
        if (!loginname) {
            loginname = '';
        }
        let deviceid = SDKManager.platform == Platform.WeiXin ? -1 : 0;
        let params = 'appid=' + this.remoteConfig.quleAppId + '&plat=' + plat + '&openid=' + openid + '&session=' + session + '&session2=' + session2 + '&loginname=' + loginname + '&deviceid=' + deviceid;
        let url = this.remoteConfig.quleServer + '/api/user/login?' + params;
        console.log('url: ' + url);
        Http.get(url, (success: boolean, res: string) => {
            if (success) {
                console.log('趣乐登录结果：' + res);
                let resObj = JSON.parse(res);
                if (resObj.code == 1) {
                    this.isLogined = true;
                    this.uid = resObj.data.uid;
                    this.session = resObj.data.session;
                    this.loginName = resObj.data.login_name;
                    onFinish && onFinish(true);
                    console.log('是否需要记录Banner:' + this.canRecordBannerOnceAfterLogin);
                    if (this.canRecordBannerOnceAfterLogin) {
                        this.record(plat, ADType.Banner);
                        this.canRecordBannerOnceAfterLogin = false;
                    }
                    console.log('是否需要记录Video:' + this.canRecordVideoOnceAfterLogin);
                    if (this.canRecordVideoOnceAfterLogin) {
                        this.record(plat, ADType.Video);
                        this.canRecordVideoOnceAfterLogin = false;
                    }
                    console.log('是否需要记录Insert:' + this.canRecordInsertOnceAfterLogin);
                    if (this.canRecordInsertOnceAfterLogin) {
                        this.record(plat, ADType.Insert);
                        this.canRecordInsertOnceAfterLogin = false;
                    }
                } else {
                    onFinish && onFinish(false);
                }
            } else {
                console.error('趣乐登录网络错误：' + res);
                onFinish && onFinish(false);
            }
        });
    }

    /**
     * 收集广告拉取数次数
     * @param plat 如：QuLe.Plat_WeiXin
     * @param adType 
     * @param onFinish: 成功返回true
     */
    record(plat: string, adType: ADType) {
        if (!this.isLogined) {
            console.log('趣乐接口尚未登录');
        }
        let type = '';
        switch (adType) {
            case ADType.Banner:
                if (!this.isLogined) {
                    this.canRecordBannerOnceAfterLogin = true;
                    return;
                }
                type = 'banner';
                break;
            case ADType.Video:
                if (!this.isLogined) {
                    this.canRecordVideoOnceAfterLogin = true;
                    return;
                }
                type = 'video';
                break;
            case ADType.Insert:
                if (!this.isLogined) {
                    this.canRecordInsertOnceAfterLogin = true;
                    return;
                }
                type = 'interstitial';
                break;
        }
        let params = 'appid=' + this.remoteConfig.quleAppId + '&plat=' + plat + '&type=' + type;
        console.log('趣乐收集广告', type, params);
        Http.get(this.remoteConfig.quleServer + '/api/ad/data?' + params, (success: boolean, res: string) => {
            if (success) {
                console.log('趣乐收集广告结果 success:' + success + ' res:' + res);
                let resObj = JSON.parse(res);
                if (resObj.code == 1) {
                    this.isLogined = true;
                }
            }
        });
    }
    /**
     * 广告跳出收集
     * @param plat 如：QuLe.PlatWeiXin
     * @param jumpto 游戏APPID 
     */
    jumpdata(jumpto: string, onFinish: Function) {
        if (!this.isLogined) {
            console.log('趣乐接口尚未登录');
            return;
        }
        let params = 'uid=' + this.uid + '&jumpto=' + jumpto;
        console.log('趣乐收集跳出', jumpto, params);
        Http.get(this.remoteConfig.quleServer + '/api/ad/jumpdata?' + params, (success: boolean, res: string) => {
            if (success) {
                console.log('趣乐收集跳出结果' + res);
                let resObj = JSON.parse(res);
                if (resObj.code == 1) {
                    onFinish && onFinish(true);
                } else {
                    onFinish && onFinish(false);
                }
            } else {
                onFinish && onFinish(false);
            }
        });
    }

}
